package com.example.screenshot_service

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.PixelFormat
import android.hardware.display.DisplayManager
import android.hardware.display.VirtualDisplay
import android.media.Image
import android.media.ImageReader
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.os.Binder
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.DisplayMetrics
import android.util.Log
import android.view.WindowManager
import androidx.core.app.NotificationCompat
import com.example.patchouli_knowledge.MainActivity
import com.example.patchouli_knowledge.R
import java.io.File
import java.io.FileOutputStream
import java.util.UUID
import java.util.concurrent.atomic.AtomicBoolean

/**
 * 持久截屏服务 - Android 14兼容版本
 * 
 * 核心功能：
 * 1. 前台服务保活机制
 * 2. MediaProjection复用，符合Android 14规范
 * 3. 单一VirtualDisplay持续使用，支持真正的多次截屏
 * 4. 智能资源管理和生命周期控制
 * 5. 防止服务被系统回收
 * 
 * Android 14适配：
 * - 遵循"一次授权，持续使用"原则
 * - 单一VirtualDisplay复用模式
 * - MediaProjection生命周期管理
 * - 配置变化自适应处理
 */
class PersistentScreenCaptureService : Service() {
    
    companion object {
        private const val TAG = "PersistentCapture"
        private const val NOTIFICATION_ID = 3001
        private const val CHANNEL_ID = "PersistentCaptureChannel"
        
        // 服务状态
        private var isServiceRunning = AtomicBoolean(false)
        
        // MediaProjection数据
        var projectionResultCode: Int = 0
        var projectionResultData: Intent? = null
        var hasProjectionPermission = false
        
        fun isRunning(): Boolean = isServiceRunning.get()
    }
    
    // Binder用于与其他组件通信
    inner class ScreenCaptureBinder : Binder() {
        fun getService(): PersistentScreenCaptureService = this@PersistentScreenCaptureService
    }
    
    private val binder = ScreenCaptureBinder()
    
    // MediaProjection相关 - 持久化资源
    private var mediaProjectionManager: MediaProjectionManager? = null
    private var mediaProjection: MediaProjection? = null
    private var persistentVirtualDisplay: VirtualDisplay? = null
    private var persistentImageReader: ImageReader? = null
    
    // 屏幕信息
    private var screenWidth = 0
    private var screenHeight = 0
    private var screenDensity = 0
    
    // 处理器和回调
    private val mainHandler = Handler(Looper.getMainLooper())
    private val captureQueue = mutableListOf<(String?) -> Unit>()
    private val isCapturing = AtomicBoolean(false)
    private val isInitialized = AtomicBoolean(false)
    
    // 统计信息
    private var screenshotCount = 0
    private var serviceStartTime = 0L
    
    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, "持久截屏服务启动 - Android 14兼容模式")
        
        serviceStartTime = System.currentTimeMillis()
        screenshotCount = 0
        
        initializeService()
        createNotificationChannel()
        startForeground(NOTIFICATION_ID, createNotification())
        isServiceRunning.set(true)
    }
    
    override fun onBind(intent: Intent?): IBinder {
        return binder
    }
    
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(TAG, "服务命令: ${intent?.action}")
        
        when (intent?.action) {
            "INIT_PROJECTION" -> {
                initializePersistentCapture()
            }
            "CAPTURE_SCREEN" -> {
                val callback = intent.getStringExtra("callback")
                captureScreen { imagePath ->
                    // 通过Intent返回结果到MainActivity
                    val resultIntent = Intent(this, MainActivity::class.java)
                    resultIntent.action = "CAPTURE_RESULT"
                    resultIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP
                    resultIntent.putExtra("imagePath", imagePath)
                    resultIntent.putExtra("success", imagePath != null)
                    startActivity(resultIntent)
                }
            }
        }
        
        // 返回START_STICKY确保服务被意外杀死后重启
        return START_STICKY
    }
    
    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "持久截屏服务销毁")
        
        releaseAllResources()
        isServiceRunning.set(false)
    }
    
    /**
     * 初始化服务
     */
    private fun initializeService() {
        mediaProjectionManager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        updateScreenMetrics()
    }
    
    /**
     * 更新屏幕参数
     */
    private fun updateScreenMetrics() {
        val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val metrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(metrics)
        
        screenWidth = metrics.widthPixels
        screenHeight = metrics.heightPixels
        screenDensity = metrics.densityDpi
        
        Log.d(TAG, "屏幕参数: ${screenWidth}x${screenHeight}, 密度: $screenDensity")
    }
    
    /**
     * 初始化持久截屏能力 - Android 14兼容版本
     * 关键：只创建一次VirtualDisplay，后续复用，不设置持续监听器
     */
    fun initializePersistentCapture(): Boolean {
        if (isInitialized.get()) {
            Log.d(TAG, "持久截屏已初始化，跳过重复初始化")
            return true
        }
        
        if (!hasProjectionPermission || projectionResultData == null) {
            Log.e(TAG, "MediaProjection权限未授予")
            return false
        }
        
        try {
            // 1. 创建MediaProjection（只创建一次）
            if (mediaProjection == null) {
                mediaProjection = mediaProjectionManager?.getMediaProjection(
                    projectionResultCode, 
                    projectionResultData!!
                )
                
                // 为Android 14+注册回调
                if (Build.VERSION.SDK_INT >= 34) {
                    try {
                        mediaProjection?.registerCallback(object : MediaProjection.Callback() {
                            override fun onStop() {
                                super.onStop()
                                Log.w(TAG, "MediaProjection已停止，需要重新授权")
                                handleProjectionStopped()
                            }
                            
                            override fun onCapturedContentResize(width: Int, height: Int) {
                                super.onCapturedContentResize(width, height)
                                Log.d(TAG, "屏幕尺寸变化: ${width}x${height}")
                                handleScreenSizeChange(width, height)
                            }
                            
                            override fun onCapturedContentVisibilityChanged(isVisible: Boolean) {
                                super.onCapturedContentVisibilityChanged(isVisible)
                                Log.d(TAG, "内容可见性变化: $isVisible")
                            }
                        }, mainHandler)
                        Log.d(TAG, "MediaProjection回调注册成功")
                    } catch (e: Exception) {
                        Log.w(TAG, "注册MediaProjection回调失败: ${e.message}")
                    }
                }
            }
            
            // 2. 创建持久ImageReader（不设置监听器）
            if (persistentImageReader == null) {
                persistentImageReader = ImageReader.newInstance(
                    screenWidth, screenHeight, 
                    PixelFormat.RGBA_8888, 2 // 减少缓冲区数量，按需使用
                )
                
                // 重要：初始化时不设置监听器，避免持续回调
                // 监听器将在每次截图请求时动态设置和清除
                
                Log.d(TAG, "持久ImageReader创建成功（无监听器）")
            }
            
            // 3. 创建持久VirtualDisplay（关键：只创建一次）
            if (persistentVirtualDisplay == null) {
                persistentVirtualDisplay = mediaProjection?.createVirtualDisplay(
                    "PersistentScreenCapture", // 使用专门的名称
                    screenWidth,
                    screenHeight,
                    screenDensity,
                    DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                    persistentImageReader?.surface,
                    null,
                    mainHandler
                )
                
                if (persistentVirtualDisplay != null) {
                    Log.d(TAG, "持久VirtualDisplay创建成功 - 按需截图模式")
                    isInitialized.set(true)
                    updateNotification()
                    return true
                } else {
                    Log.e(TAG, "持久VirtualDisplay创建失败")
                    return false
                }
            }
            
            return true
            
        } catch (e: SecurityException) {
            Log.e(TAG, "SecurityException - Android 14权限限制: ${e.message}")
            handleProjectionStopped()
            return false
        } catch (e: Exception) {
            Log.e(TAG, "初始化持久截屏失败: ${e.message}")
            return false
        }
    }
    
    /**
     * 执行截屏 - 按需触发模式（Android 14兼容）
     * 关键：只有在明确请求时才进行一次截图，避免持续回调
     */
    fun captureScreen(callback: (String?) -> Unit) {
        Log.d(TAG, "收到截图请求 - 按需触发模式")
        
        // 检查初始化状态
        if (!isInitialized.get()) {
            Log.w(TAG, "持久截屏未初始化，尝试初始化")
            if (!initializePersistentCapture()) {
                Log.e(TAG, "初始化失败，截屏取消")
                callback(null)
                return
            }
        }
        
        // 检查是否正在截图
        if (isCapturing.get()) {
            Log.w(TAG, "正在截图中，将请求加入队列等待")
            synchronized(captureQueue) {
                captureQueue.add(callback)
            }
            return
        }
        
        // 检查资源状态
        if (persistentVirtualDisplay == null || persistentImageReader == null) {
            Log.e(TAG, "持久资源不可用，截屏取消")
            callback(null)
            return
        }
        
        // 设置截图状态
        isCapturing.set(true)
        
        // 添加到截屏队列
        synchronized(captureQueue) {
            captureQueue.add(callback)
            Log.d(TAG, "截屏请求加入队列，当前队列长度: ${captureQueue.size}")
        }
        
        // 执行单次截图
        executeSingleScreenshot()
    }
    
    /**
     * 执行单次截图 - 改进版本
     * 使用临时ImageReader来确保只触发一次截图
     */
    private fun executeSingleScreenshot() {
        try {
            Log.d(TAG, "开始执行单次截图")
            
            // 创建临时的ImageReader专门用于这次截图
            val tempImageReader = ImageReader.newInstance(
                screenWidth, screenHeight, 
                PixelFormat.RGBA_8888, 1
            )
            
            // 为临时ImageReader设置一次性监听器
            tempImageReader.setOnImageAvailableListener({ reader ->
                Log.d(TAG, "收到单次截图回调，开始处理")
                
                // 处理这次截图
                processSingleScreenshot(reader)
                
                // 立即清理临时ImageReader
                mainHandler.post {
                    try {
                        reader.close()
                        Log.d(TAG, "临时ImageReader已清理")
                    } catch (e: Exception) {
                        Log.w(TAG, "清理临时ImageReader失败: ${e.message}")
                    }
                }
            }, mainHandler)
            
            // 将VirtualDisplay的Surface切换到临时ImageReader
            val tempSurface = tempImageReader.surface
            if (tempSurface != null && tempSurface.isValid) {
                persistentVirtualDisplay?.setSurface(tempSurface)
                Log.d(TAG, "VirtualDisplay已切换到临时Surface，等待截图")
                
                // 设置超时后切换回原始Surface
                mainHandler.postDelayed({
                    try {
                        // 切换回原始Surface
                        persistentVirtualDisplay?.setSurface(persistentImageReader?.surface)
                        Log.d(TAG, "VirtualDisplay已切换回原始Surface")
                        
                        // 如果还在截图状态，说明超时了
                        if (isCapturing.get()) {
                            Log.w(TAG, "截图超时，处理失败回调")
                            processTimeoutCallbacks()
                        }
                    } catch (e: Exception) {
                        Log.e(TAG, "切换Surface失败: ${e.message}")
                        processFailedCallbacks()
                    }
                }, 3000) // 3秒超时
                
            } else {
                Log.e(TAG, "临时Surface无效，无法执行截图")
                tempImageReader.close()
                processFailedCallbacks()
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "执行单次截图失败: ${e.message}")
            processFailedCallbacks()
        }
    }
    
    /**
     * 处理单次截图
     */
    private fun processSingleScreenshot(reader: ImageReader) {
        var image: Image? = null
        var bitmap: Bitmap? = null
        var fos: FileOutputStream? = null
        
        try {
            Log.d(TAG, "开始处理单次截图图像")
            
            image = reader.acquireLatestImage()
            if (image != null) {
                // 从Image创建Bitmap
                val planes = image.planes
                val buffer = planes[0].buffer
                val pixelStride = planes[0].pixelStride
                val rowStride = planes[0].rowStride
                val rowPadding = rowStride - pixelStride * screenWidth
                
                bitmap = Bitmap.createBitmap(
                    screenWidth + rowPadding / pixelStride,
                    screenHeight,
                    Bitmap.Config.ARGB_8888
                )
                bitmap.copyPixelsFromBuffer(buffer)
                
                // 保存截图
                val screenshotFile = createScreenshotFile()
                fos = FileOutputStream(screenshotFile)
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)
                
                Log.d(TAG, "单次截图保存成功: ${screenshotFile.absolutePath}")
                
                // 更新统计信息
                screenshotCount++
                
                // 处理队列中的回调
                mainHandler.post {
                    processSuccessCallbacks(screenshotFile.absolutePath)
                    updateNotification()
                }
                
            } else {
                Log.e(TAG, "获取单次截图图像失败")
                mainHandler.post {
                    processFailedCallbacks()
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "处理单次截图图像失败: ${e.message}")
            mainHandler.post {
                processFailedCallbacks()
            }
        } finally {
            // 确保资源正确释放
            try {
                image?.close()
                bitmap?.recycle()
                fos?.close()
            } catch (e: Exception) {
                Log.w(TAG, "释放单次截图资源时出错: ${e.message}")
            }
        }
    }
    
    /**
     * 处理成功的回调
     */
    private fun processSuccessCallbacks(imagePath: String) {
        synchronized(captureQueue) {
            val callbacks = captureQueue.toList()
            captureQueue.clear()
            
            Log.d(TAG, "处理${callbacks.size}个成功回调")
            callbacks.forEach { callback ->
                try {
                    callback(imagePath)
                } catch (e: Exception) {
                    Log.e(TAG, "回调执行失败: ${e.message}")
                }
            }
        }
        isCapturing.set(false)
    }
    
    /**
     * 处理失败的回调
     */
    private fun processFailedCallbacks() {
        synchronized(captureQueue) {
            val callbacks = captureQueue.toList()
            captureQueue.clear()
            
            Log.d(TAG, "处理${callbacks.size}个失败回调")
            callbacks.forEach { callback ->
                try {
                    callback(null)
                } catch (e: Exception) {
                    Log.e(TAG, "失败回调执行失败: ${e.message}")
                }
            }
        }
        isCapturing.set(false)
    }
    
    /**
     * 处理超时的回调
     */
    private fun processTimeoutCallbacks() {
        Log.w(TAG, "截图超时，清理队列")
        processFailedCallbacks()
    }
    
    /**
     * 处理MediaProjection停止事件
     */
    private fun handleProjectionStopped() {
        Log.w(TAG, "MediaProjection已停止，重置状态")
        
        isInitialized.set(false)
        hasProjectionPermission = false
        
        // 不释放资源，等待重新授权
        mediaProjection = null
        
        // 通知MainActivity需要重新授权
        val intent = Intent(this, MainActivity::class.java)
        intent.action = "PROJECTION_STOPPED"
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP
        startActivity(intent)
        
        updateNotification()
    }
    
    /**
     * 处理屏幕尺寸变化
     */
    private fun handleScreenSizeChange(width: Int, height: Int) {
        Log.d(TAG, "处理屏幕尺寸变化: ${width}x${height}")
        
        // 更新屏幕参数
        screenWidth = width
        screenHeight = height
        
        // 调整VirtualDisplay尺寸（不重新创建）
        try {
            persistentVirtualDisplay?.resize(width, height, screenDensity)
            Log.d(TAG, "VirtualDisplay尺寸调整成功")
        } catch (e: Exception) {
            Log.e(TAG, "VirtualDisplay尺寸调整失败: ${e.message}")
        }
    }
    
    /**
     * 创建截图文件
     */
    private fun createScreenshotFile(): File {
        val timestamp = System.currentTimeMillis()
        val uuid = UUID.randomUUID().toString().substring(0, 8)
        val fileName = "persistent_screenshot_${timestamp}_$uuid.png"
        
        val docDir = File(filesDir, "doc")
        if (!docDir.exists()) {
            docDir.mkdirs()
        }
        
        return File(docDir, fileName)
    }
    
    /**
     * 释放所有资源
     */
    private fun releaseAllResources() {
        Log.d(TAG, "释放所有资源")
        
        // 清理队列
        synchronized(captureQueue) {
            captureQueue.clear()
        }
        
        // 释放VirtualDisplay
        persistentVirtualDisplay?.release()
        persistentVirtualDisplay = null
        
        // 释放ImageReader
        persistentImageReader?.close()
        persistentImageReader = null
        
        // 停止MediaProjection
        mediaProjection?.stop()
        mediaProjection = null
        
        // 重置状态
        isInitialized.set(false)
        isCapturing.set(false)
        hasProjectionPermission = false
        projectionResultData = null
    }
    
    /**
     * 创建通知渠道
     */
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "知拾截屏服务",
                NotificationManager.IMPORTANCE_DEFAULT
            ).apply {
                description = "保持截屏权限活跃，支持悬浮球快速多次截屏。关闭此通知可能导致截屏功能失效。"
                setShowBadge(true)
                enableLights(false)
                enableVibration(false)
                setSound(null, null)
                lockscreenVisibility = Notification.VISIBILITY_PUBLIC
                setBypassDnd(false)
            }
            
            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }
    
    /**
     * 更新通知内容
     */
    private fun updateNotification() {
        try {
            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.notify(NOTIFICATION_ID, createNotification())
        } catch (e: Exception) {
            Log.e(TAG, "更新通知失败: ${e.message}")
        }
    }
    
    /**
     * 创建前台服务通知
     */
    private fun createNotification(): Notification {
        val intent = Intent(this, MainActivity::class.java)
        val pendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
        } else {
            PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
        }

        // 计算运行时长
        val runningTime = if (serviceStartTime > 0) {
            val minutes = (System.currentTimeMillis() - serviceStartTime) / 60000
            if (minutes < 60) "${minutes}分钟" else "${minutes/60}小时${minutes%60}分钟"
        } else "刚启动"
        
        val statusText = when {
            !isInitialized.get() -> "等待权限授权 • 点击管理"
            screenshotCount > 0 -> "已截图${screenshotCount}次 • 运行${runningTime} • 支持连续截屏"
            else -> "Android 14兼容模式 • 支持多次快速截屏 • 点击管理"
        }
        
        val titleText = if (isInitialized.get()) {
            "知拾截屏服务运行中（多次截屏模式）"
        } else {
            "知拾截屏服务（等待授权）"
        }
        
        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle(titleText)
            .setContentText(statusText)
            .setSubText("Android 14兼容 • MediaProjection复用模式")
            .setSmallIcon(R.mipmap.launcher_icon)
            .setContentIntent(pendingIntent)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setOngoing(true)
            .setAutoCancel(false)
            .setShowWhen(true)
            .setUsesChronometer(false)
            .setCategory(NotificationCompat.CATEGORY_SERVICE)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE)
            .addAction(
                R.mipmap.launcher_icon,
                "立即截屏",
                createScreenshotPendingIntent()
            )
            .addAction(
                R.mipmap.launcher_icon,
                "打开应用",
                pendingIntent
            )
            .setStyle(NotificationCompat.BigTextStyle()
                .bigText("知拾截屏服务采用Android 14兼容的单一VirtualDisplay复用模式，支持真正的多次快速截屏，无需重复授权。")
                .setBigContentTitle(titleText)
                .setSummaryText("VirtualDisplay复用 • 支持连续截屏"))
            .build()
    }
    
    /**
     * 创建截屏按钮的PendingIntent
     */
    private fun createScreenshotPendingIntent(): PendingIntent {
        val intent = Intent(this, PersistentScreenCaptureService::class.java).apply {
            action = "CAPTURE_SCREEN"
        }
        
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            PendingIntent.getService(this, 1, intent, PendingIntent.FLAG_IMMUTABLE)
        } else {
            PendingIntent.getService(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT)
        }
    }
    
    /**
     * 检查服务是否健康
     */
    fun isServiceHealthy(): Boolean {
        return isInitialized.get() && persistentVirtualDisplay != null && !isCapturing.get()
    }
    
    /**
     * 获取服务状态信息
     */
    fun getServiceStatus(): Map<String, Any> {
        return mapOf(
            "isRunning" to isServiceRunning.get(),
            "isInitialized" to isInitialized.get(),
            "hasProjection" to (mediaProjection != null),
            "hasVirtualDisplay" to (persistentVirtualDisplay != null),
            "isCapturing" to isCapturing.get(),
            "queueSize" to captureQueue.size,
            "screenshotCount" to screenshotCount,
            "screenSize" to "${screenWidth}x${screenHeight}"
        )
    }
} 